<?php
/**
 * Created by jinqiang on 2024/7/10 10:26.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Repository;


use App\Http\Models\Mysql\SsyConfigTable;
use App\Http\Models\Mysql\SsyProcessingFactoryNameTable;

class EqbRepository
{
    private $_app_id;

    private $_secret;

    private $_access_token;

    private $_sealId;

    private $_tmpId;//pdf模板id

    private $host = "https://openapi.esign.cn";

    public function __construct($sub = "kz")
    {
        $subjects = array_column(config('scm.subject'), null, 'is_subject');
        $this->_app_id = $subjects[$sub]['eqb_app_id'];
        $this->_secret = $subjects[$sub]['eqb_secret'];
        $this->_sealId = $subjects[$sub]['eqb_seal_id'];
        $this->_tmpId = $subjects[$sub]['eqb_tmp_id'];
        $res = $this->createAccessToken();
        $this->_access_token = $res['data']['token'] ?? "";
    }

    //获取token
    public function createAccessToken()
    {
        $url = $this->host."/v1/oauth2/access_token?appId={$this->_app_id}&secret={$this->_secret}&grantType=client_credentials";
        $resp = httpCurl($url, "", "get");
        return json_decode($resp, true);
    }

    //创建企业账号
    public function createOrganizations($data)
    {
        $url = $this->host.'/v1/organizations/createByThirdPartyUserId';
        $param = [
            "headers" => [
                'X-Tsign-Open-Token:'.$this->_access_token,
                'X-Tsign-Open-App-Id:'.$this->_app_id,
                'Content-Type:application/json;charset=UTF-8',
            ],
            "json" => json_encode([
                "idType" => "CRED_ORG_USCC",
                "thirdPartyUserId" => $data['thirdPartyUserId'],
                "name" => $data['name'],
                "idNumber" => $data['idNumber']
            ])
        ];
        $resp = httpCurl($url, $param);
        return json_decode($resp,true);
    }

    //创建个人账号
    public function createAccounts($data)
    {
        $url = $this->host.'/v1/accounts/createByThirdPartyUserId';
        $param = [
            "headers" => [
                'X-Tsign-Open-Token:'.$this->_access_token,
                'X-Tsign-Open-App-Id:'.$this->_app_id,
                'Content-Type:application/json;charset=UTF-8',
            ],
            "json" => json_encode([
                "idType" => "CRED_PSN_CH_IDCARD",
                "thirdPartyUserId" => $data['thirdPartyUserId'],
                "name" => $data['name'],
                "idNumber" => $data['idNumber'],
                "mobile" => $data['mobile']
            ])
        ];
        $resp = httpCurl($url, $param);
        return json_decode($resp,true);
    }

    //修改个人签署账号（通过user_account_id修改）
    public function setUserAccounts($userAccountId, $data)
    {
        $url = $this->host."/v1/accounts/{$userAccountId}";
        $param = [
            "headers" => [
                'X-Tsign-Open-Token:'.$this->_access_token,
                'X-Tsign-Open-App-Id:'.$this->_app_id,
                'Content-Type:application/json;charset=UTF-8',
            ],
            "json" => json_encode($data)
        ];
        $resp = httpCurl($url, $param, 'put');
        return json_decode($resp,true);
    }

    //修改机构签署账号（通过orgId修改）
    public function setOrgAccounts($orgId, $data)
    {
        $url = $this->host."/v1/organizations/{$orgId}";
        $param = [
            "headers" => [
                'X-Tsign-Open-Token:'.$this->_access_token,
                'X-Tsign-Open-App-Id:'.$this->_app_id,
                'Content-Type:application/json;charset=UTF-8',
            ],
            "json" => json_encode($data)
        ];
        $resp = httpCurl($url, $param, 'put');
        return json_decode($resp,true);
    }

    //发起签署
    public function signflows($data)
    {
        $url = $this->host.'/api/v2/signflows/createFlowOneStep';
        //机构签署
        $postData = [
            "docs" => [
                [
                    "fileId" => $data['fileid'],
                    "fileName" => $data['factory_name']."采购合同.pdf"
                ]
            ],
            "flowInfo" => [
                "autoArchive" => false,
                "autoInitiate" => true,
                "businessScene" => $data['factory_contract_no'],
                "flowConfigInfo" => [
                    "noticeDeveloperUrl" => "https://nnyy.13yu.com/api/cb/eqb/sign",
                    "redirectUrl" => "",
                    "signPlatform" => "1"
                ]
            ],
            "signers" => [
                [
                    "platformSign" => true,
                    "signOrder" => 1,
                    "signerAccount" => ["signerAccountId" => "", "authorizedAccountId" => ""],
                    "signfields" => [
                        [
                            "autoExecute" => true,
                            "actorIndentityType" => 2,
                            "fileId" => $data['fileid'],
                            "sealType" => "1",
                            "posBean" => ["posPage" => "1", "posX" => "85", "posY" => "63"]
                        ]
                    ]
                ],
                [
                    "platformSign" => false,
                    "signOrder" => 1,
                    "signerAccount" => ["signerAccountId" => $data['signeraccountid'], "authorizedAccountId" => $data['signerorgid']],
                    "signfields" => [
                        [
                            "autoExecute" => false,
                            "actorIndentityType" => 2,
                            "fileId" => $data['fileid'],
                            "sealType" => "1",
                            "posBean" => ["posPage" => "1", "posX" => "380", "posY" => "60"]
                        ]
                    ]
                ]
            ]
        ];
        //个人签署
        /*
        $postData = [
            "docs" => [
                "fileId" => $data['fileid'],
                "fileName" => $data['factory_name']."采购合同.pdf"
            ],
            "flowInfo" => [
                "autoArchive" => true,
                "autoInitiate" => true,
                "businessScene" => "十三余",
                "flowConfigInfo" => [
                    "noticeDeveloperUrl" => "https://nnyy.13yu.com/api/cb/eqb/sign",
                    "redirectUrl" => "",
                    "signPlatform" => "1"
                ]
            ],
            "signers" => [
                [
                    "platformSign" => true,
                    "signOrder" => 1,
                    "signerAccount" => ["signerAccountId" => "", "authorizedAccountId" => ""],
                    "signfields" => [
                        [
                            "autoExecute" => true,
                            "actorIndentityType" => 2,
                            "fileId" => $data['fileid'],
                            "sealType" => "1",
                            "posBean" => ["posPage" => "1", "posX" => "85", "posY" => "63"]
                        ]
                    ]
                ],
                [
                    "platformSign" => false,
                    "signOrder" => 1,
                    "signerAccount" => ["signerAccountId" => $data['signeraccountid']],
                    "signfields" => [
                        [
                            "autoExecute" => false,
                            "fileId" => $data['fileid'],
                            "sealType" => "0",
                            "posBean" => ["posPage" => "1", "posX" => "380", "posY" => "63"]
                        ]
                    ]
                ]
            ]
        ];*/
        $param = [
            "headers" => [
                'X-Tsign-Open-Token:'.$this->_access_token,
                'X-Tsign-Open-App-Id:'.$this->_app_id,
                'Content-Type:application/json;charset=UTF-8',
            ],
            "json" => json_encode($postData, JSON_UNESCAPED_UNICODE)
        ];
        $resp = httpCurl($url, $param);
        return json_decode($resp,true);
    }

    //附件合同
    public function signUrl($data)
    {
        $url = $this->host."/v1/signflows/{$data['flowId']}/executeUrl?accountId={$data['accountId']}&organizeId={$data['organizeId']}&urlType={$data['urlType']}";
        $param = [
            "headers" => [
                'X-Tsign-Open-Token:'.$this->_access_token,
                'X-Tsign-Open-App-Id:'.$this->_app_id,
                'Content-Type:application/json;charset=UTF-8',
            ]
        ];
        $resp = httpCurl($url, $param, 'get');
        return json_decode($resp,true);
    }

    //生成pdf合同文件
    public function createPdf($data, $processingList)
    {
        $factoryList = (new SsyProcessingFactoryNameTable())->whereIn('supplier_id', [$data['supplier_id'], $data['source_factory_groups_id']])->get()->toArray();
        $factoryMap = array_column($factoryList, null, 'supplier_id');
        //甲方信息
        $factoryA = $factoryMap[$data['source_factory_groups_id']];
        //乙方信息
        $factoryB = $factoryMap[$data['supplier_id']];
        if(empty($factoryB['legal_person']) || empty($factoryB['contact_address']) || empty($factoryB['bank_of_deposit'])){
            return ['code' => -1, 'msg' => '工厂信息不全，合同生成失败！'];
        }
        //配置信息
        $configObj = (new SsyConfigTable())->where('id', 1)->first(["part_A_place","part_A_receive","part_A_receive_tel"])->toArray();
        list($totalAmount, $totalNum, $detail) = [0, 0, []];
        foreach ($processingList as $item){
            $totalNum += $item['num'];
            $totalAmount += $item['num'] * $item['unit_price'];
            //尺码数 XXL 150
            $XXLRow = in_array($item['size_code'], ["XXL", "150"]) ? $item['num'] : "";
            //尺码数 XL 140
            $XLRow = in_array($item['size_code'], ["XL", "140"]) ? $item['num'] : "";
            //尺码数 L 130
            $LRow = in_array($item['size_code'], ["L", "130"]) ? $item['num'] : "";
            //尺码数 M 120
            $MRow = in_array($item['size_code'], ["M", "120"]) ? $item['num'] : "";
            //尺码数 S 110
            $SRow = in_array($item['size_code'], ["S", "110"]) ? $item['num'] : "";
            //尺码数 XS 100
            $XSRow = in_array($item['size_code'], ["XS", "100"]) ? $item['num'] : "";
            //尺码数 XXS 90
            $XXSRow = in_array($item['size_code'], ["XXS", "90"]) ? $item['num'] : "";
            if(isset($detail[$item['processing_code']])){
                !empty($XXLRow) && $detail[$item['processing_code']]['XXLRow'] = $XXLRow;
                !empty($XLRow) && $detail[$item['processing_code']]['XLRow'] = $XLRow;
                !empty($LRow) && $detail[$item['processing_code']]['LRow'] = $LRow;
                !empty($MRow) && $detail[$item['processing_code']]['MRow'] = $MRow;
                !empty($SRow) && $detail[$item['processing_code']]['SRow'] = $SRow;
                !empty($XSRow) && $detail[$item['processing_code']]['XSRow'] = $XSRow;
                !empty($XXSRow) && $detail[$item['processing_code']]['XXSRow'] = $XXSRow;
            }else{
                $detail[$item['processing_code']] = [
                    "processing_code" => $item['processing_code'],
                    "type_no" => $item['type_no'],
                    "type_name" => mb_strlen($item['type_name']) >= 24 ? mb_substr($item['type_name'], 0, 22)."..." : $item['type_name'],
                    "color_code" => $item['color_code'],
                    "unit_price" => $item['unit_price'],
                    "countnum" => $item['countnum'],
                    "countprice" => $item['countprice'],
                    "order_processor" => $item['order_processor'],
                    "jy_number" => $item['jy_number'],
                    "XXLRow" => $XXLRow ?: "--",
                    "XLRow" => $XLRow ?: "--",
                    "LRow" => $LRow ?: "--",
                    "MRow" => $MRow ?: "--",
                    "SRow" => $SRow ?: "--",
                    "XSRow" => $XSRow ?: "--",
                    "XXSRow" => $XXSRow ?: "--",
                    "contract_date" => $item['contract_date']
                ];
            }
        }
        if(count($detail)>20 || count($detail)==0){
            return ['code' => -1, 'msg' => '加工单数量超20或没有加工单，不可生成合同！'];
        }
        $totalAmountCap = amountNumToZn($totalAmount);
        $list = array_values($detail);
        $postData = [
            "name" => "采购合同.pdf",
            "templateId" => $this->_tmpId,
            "simpleFormFields" => [
                "factory_contract_no" => $data['factory_contract_no'],
                "sign_date" => date('Y-m-d'),
                "total_num" => $totalNum,
                "total" => "￥".sprintf("%1\$.2f", $totalAmount),
                "total_cap" => $totalAmountCap,
                "part_A_place" => $configObj['part_A_place'],
                "part_A_receive" => $configObj['part_A_receive'],
                "part_A_receive_tel" => $configObj['part_A_receive_tel'],
                "part_A_name" => $factoryA['company_head'],
                "part_A_legal" => $data['order_processor'],
                "part_A_contact" => $factoryA['contact_phone'],
                "part_A_address" => $factoryA['contact_address'],
                "part_B_name" => $factoryB['company_head'],
                "part_B_legal" => $factoryB['legal_person'],
                "part_B_contact" => $factoryB['contact_phone'],
                "part_B_address" => $factoryB['contact_address']
            ],
        ];
        for($i = 1; $i <= 20; $i++){
            $rowData = [
                "typenoRow{$i}" => $list[$i-1]['type_no'] ?? "",
                "poidRow{$i}" => $list[$i-1]['jy_number'] ?? "",
                "processingcodRow{$i}" => $list[$i-1]['processing_code'] ?? "",
                "nameRow{$i}" => $list[$i-1]['type_name'] ?? "",
                "colorRow{$i}" => $list[$i-1]['color_code'] ?? "",
                "XXSRow{$i}" => $list[$i-1]['XXSRow'] ?? "",
                "XSRow{$i}" => $list[$i-1]['XSRow'] ?? "",
                "SRow{$i}" => $list[$i-1]['SRow'] ?? "",
                "MRow{$i}" => $list[$i-1]['MRow'] ?? "",
                "LRow{$i}" => $list[$i-1]['LRow'] ?? "",
                "XLRow{$i}" => $list[$i-1]['XLRow'] ?? "",
                "XXLRow{$i}" => $list[$i-1]['XXLRow'] ?? "",
                "coutnumRow{$i}" => $list[$i-1]['countnum'] ?? "",
                "priceRow{$i}" => $list[$i-1]['unit_price'] ?? "",
                "amountRow{$i}" => $list[$i-1]['countprice'] ?? "",
                "adddateRow{$i}" => $list[$i-1]['contract_date'] ?? "",
            ];
            $postData['simpleFormFields'] = array_merge($postData['simpleFormFields'], $rowData);
        }
        $url = $this->host.'/v1/files/createByTemplate';
        $param = [
            "headers" => [
                'X-Tsign-Open-Token:'.$this->_access_token,
                'X-Tsign-Open-App-Id:'.$this->_app_id,
                'Content-Type:application/json;charset=UTF-8',
            ],
            "json" => json_encode($postData, JSON_UNESCAPED_UNICODE)
        ];
        $resp = httpCurl($url, $param);
        return json_decode($resp,true);
    }

    //发起部门章
    public function signflowsBumen($data)
    {
        $url = $this->host.'/api/v2/signflows/createFlowOneStep';
        $postData = [
            "docs" => [
                [
                    "fileId" => $data['fileid'],
                    "fileName" => $data['factory_name']."采购合同.pdf"
                ]
            ],
            "flowInfo" => [
                "autoArchive" => false,
                "autoInitiate" => true,
                "businessScene" => "十三余",
                "flowConfigInfo" => [
                    "noticeDeveloperUrl" => "https://nnyy.13yu.com/api/cb/eqb/sign",
                    "redirectUrl" => "",
                    "signPlatform" => "1"
                ]
            ],
            "signers" => [
                [
                    "platformSign" => true,
                    "signOrder" => 1,
                    "signerAccount" => ["signerAccountId" => "", "authorizedAccountId" => ""],
                    "signfields" => [
                        [
                            "autoExecute" => true,
                            "actorIndentityType" => 2,
                            "fileId" => $data['fileid'],
                            "sealId" => $this->_sealId,
                            "sealType" => "1",
                            "posBean" => ["posPage" => "1", "posX" => "20", "posY" => "200"]
                        ]
                    ]
                ]
            ]
        ];
        $param = [
            "headers" => [
                'X-Tsign-Open-Token:'.$this->_access_token,
                'X-Tsign-Open-App-Id:'.$this->_app_id,
                'Content-Type:application/json;charset=UTF-8',
            ],
            "json" => json_encode($postData, JSON_UNESCAPED_UNICODE)
        ];
        $resp = httpCurl($url, $param);
        return json_decode($resp,true);
    }
}
